/*
 * Copyright (C) 2010 TopCoder Inc., All Rights Reserved.
 */
package com.hercules.android.receiver.commands.call.animate;

import android.os.Handler;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Transformation;

import com.hercules.android.receiver.Receiver;
import com.hercules.android.receiver.ReceiverUtil;
import com.hercules.android.receiver.commands.XRECommandHandlerException;
import com.hercules.android.receiver.entities.XREAlphaAnimation;
import com.hercules.android.receiver.entities.XREObject;
import com.hercules.android.receiver.entities.XREView;

/**
 * <p>
 * This class will handle the XREAlphaAnimation animation.
 * </p>
 * 
 * @author TCSASSEMBER
 * @version 1.0
 */
public class XREHandlerAlphaAnimate implements XREHandlerAnimate {
    /**
     * Handle the animate call command message.
     * 
     * @param targetView
     *            the target view need to animate
     * @param animationResource
     *            the animation resource
     * @param receiver
     *            the <code>Receiver</code> instance.
     * @throws XRECommandHandlerException
     *             if any error occurs
     */
    public void handle(final XREView targetView, final XREObject animationResource, final Receiver receiver)
            throws XRECommandHandlerException {
        XREAlphaAnimation animation = (XREAlphaAnimation) animationResource;

        final Animation alphaAnimation = new AlphaAnimation(targetView.getAlpha().floatValue(), animation.getAlpha()
                .floatValue());
        alphaAnimation.setDuration(animation.getDuration());
        new Thread(new Runnable() {
            /**
             * The method function of the thread. It will update the states of
             * the target and update the root view.
             */
            public void run() {
                Transformation transformation = new Transformation();
                while (true) {
                    if (alphaAnimation.hasEnded()) {
                        return;
                    }
                    alphaAnimation.getTransformation(AnimationUtils.currentAnimationTimeMillis(), transformation);
                    targetView.setAlpha((double) transformation.getAlpha());
                    // redraw the view
                    Handler mHandler = receiver.getApplicationData().getRootViewUpdateHandler();
                    mHandler.sendMessage(mHandler.obtainMessage());
                    ReceiverUtil.animateSleep();
                }
            }
        }).start();
        alphaAnimation.startNow();
    }
}
